import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'
import { getToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import { getUserRoutes } from '@/api/module/routers'

const whiteList = ['/login', '/auth-redirect'] // 不需要重定向的白名单

NProgress.configure({ easing: 'ease', showSpinner: false })

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  // 设置页面表头名字
  document.title = getPageTitle(to.meta['title'])
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已经登录了则重定向到首页
      next({ path: '/' })
      NProgress.done()
    } else {
      const allowAccessTo = await store.dispatch('authorityVerification', to)
      const hasUser = store.state.user.username // 这里应对应唯一用户id
      if (allowAccessTo && hasUser) {
        next()
      } else if (hasUser) {
        // 在存在用户信息的情况下 这是不存在权限
        next({ path: '/404', replace: true })
      } else {
        try {
          const { data } = await store.dispatch('getUserInfo', { token: getToken() })
          const { data: asyncRoutes } = await getUserRoutes({ role: data.roles[0] })
          await store.dispatch('generateRoutes', asyncRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          ElMessage.error('路由信息获取失败!')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
